package cn.mrx.eas.controller;

import cn.mrx.eas.dto.sys.SysRole;
import cn.mrx.eas.dto.sys.SysUser;
import cn.mrx.eas.server.BSGrid;
import cn.mrx.eas.server.ServerResponse;
import cn.mrx.eas.service.sys.ISysRoleService;
import cn.mrx.eas.shiro.EasRealm;
import cn.mrx.eas.vo.sys.TreeNode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * Author: Mr.X
 * Date: 2017/12/24 上午11:28
 * Description:
 */
@Controller
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private EasRealm easRealm;

    // 角色列表页面
    @RequiresPermissions("sys:role:list")
    @GetMapping
    public String index() {
        return "sys/role";
    }

    // 分页查询角色逻辑
    @RequiresPermissions("sys:role:list")
    @PostMapping("/list")
    @ResponseBody
    public BSGrid list(Integer curPage, Integer pageSize) {
        return iSysRoleService.roleListPage(curPage, pageSize);
    }

    // 编辑角色页面
    @RequiresPermissions("sys:role:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, Model model) {
        SysRole sysRole = iSysRoleService.findOneById(id);
        model.addAttribute("sysRole", sysRole);
        return "sys/role-edit";
    }

    // 查询该角色所拥有的权限节点(编辑角色会用到)
    @RequiresPermissions("sys:role:allNodes")
    @PostMapping("/allNodes")
    @ResponseBody
    public List<TreeNode> allNodes(Integer roleId) {
        return iSysRoleService.allNodes(roleId);
    }

    // 编辑角色逻辑
    @RequiresPermissions("sys:role:edit")
    @PostMapping("/edit")
    @ResponseBody
    public ServerResponse edit(SysRole sysRole, String permissionIds) {
        ServerResponse serverResponse = iSysRoleService.editRole(sysRole, permissionIds);
        if (serverResponse.isSuccess()) {
            // 清除权限缓存
            easRealm.clearCached();
        }
        return serverResponse;
    }

    // 添加角色页面
    @RequiresPermissions("sys:role:add")
    @GetMapping("/add")
    public String add() {
        return "sys/role-add";
    }

    // 添加角色逻辑
    @RequiresPermissions("sys:role:add")
    @PostMapping("/add")
    @ResponseBody
    public ServerResponse add(SysRole sysRole, String permissionIds) {
        // 创建者
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        sysRole.setCreateUserId(sysUser.getId());
        return iSysRoleService.addRole(sysRole, permissionIds);
    }

    // 批量删除角色逻辑
    @RequiresPermissions("sys:role:batchDel")
    @PostMapping("/batchDel")
    @ResponseBody
    public ServerResponse batchDel(String ids) {
        return iSysRoleService.batchDel(ids);
    }
}